package com.itheima.chapter12.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
反射类中的构造方法，随后创造对象
 */
public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //通过class的静态方法 forName
        Class<?> aClass = Class.forName("com.itheima.chapter12.reflect.Domain.Student");
        System.out.println(aClass);
        System.out.println("------------返回所有构造方法对象数组-------------");
        Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        System  .out.println("----------返回所有公共构造方法对象数组---------------");
        Constructor<?>[] constructors = aClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System  .out.println("----------返回单个公共构造方法对象---------------");
        Constructor<?> constructor = aClass.getConstructor();
        System.out.println(constructor);
        System  .out.println("----------返回单个构造方法对象---------------");
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class,int.class);
        System.out.println(declaredConstructor);
        //取消访问检查，打开权限
        declaredConstructor.setAccessible(true);

        //通过构造方法对像，完成实例化
        Object o = declaredConstructor.newInstance("张三", 23);
        System.out.println(o);
        Object o1 = constructor.newInstance();
        System.out.println(o1);
    }

}
